package com.lanchewuyou.user.driver.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.Utils.NetUtils;
import com.lanchewuyou.user.driver.Utils.TUtils;
import com.lanchewuyou.user.driver.lipeiui.PickCarActivity;
import com.lanchewuyou.user.driver.lipeiui.PickCarOverActivity;
import com.lanchewuyou.user.driver.lipeiui.RerurnCarOverActivity;
import com.lanchewuyou.user.driver.lipeiui.ReturnCarActivity;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.LocationApplication;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 录入信息后选择导航界面
 */

public class StartDaohangActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private TextView myLocationText,targetLocationText;
    private Button startDaohang,endDaohang;
    private LocationClient mLocationClient;
    private BDLocation location;
    //常用地图及导航app包名
    String [] packageNames=new String[]{"com.autonavi.minimap","com.google.android.apps.maps","com.baidu.BaiduMap",
            "com.baidu.navi","com.tencent.map","cld.navi.mainframe","com.autonavi.xmgd.navigator","com.sogou.map.android.maps"};
    String [] appNames=new String[]{"高德地图","Google Map","百度地图","百度导航","腾讯地图","凯立德导航","高德导航","搜狗地图"};

    private String la,lo,id;
    private static String DRIVERID;
    private String url;

    public static StartDaohangActivity instance;
    private String FROMWHERE;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    location = ((LocationApplication) getApplication()).personLocation;
                    la=location.getLatitude()+"";
                    lo=location.getLongitude()+"";
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent=getIntent();
        FROMWHERE=intent.getStringExtra("from");
        if (FROMWHERE.equals("pickcar")){
            id= PickCarActivity.orderId;
            url= Config.PICKCARDAOHANG;
        }else if (FROMWHERE.equals("returncar")){
             id= ReturnCarActivity.ORDERID;
            url=Config.RETURNCARDAOHANG;
        }
        SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        DRIVERID = sharedPreferences.getString("driverid", "");
        if(null != savedInstanceState)
        {
            FROMWHERE = savedInstanceState.getString("fromwhere");
             id = savedInstanceState.getString("saveid");
            DRIVERID = savedInstanceState.getString("savedriverid");
             url = savedInstanceState.getString("saveurl");
        }
        setContentView(R.layout.activity_start_daohang);
        mLocationClient = ((LocationApplication)getApplication()).mLocationClient;
        initLocation();
        initViews();
        instance=this;
        if (NetUtils.isConnected(StartDaohangActivity.this)) {
            if (NetUtils.isGps(StartDaohangActivity.this)) {
                mLocationClient.start();//开启定位
                Message message=new Message();
                message.what=1;
                handler.sendMessageDelayed(message,200);
            }else {
                showLocationSetting();
            }
        }else {
            TUtils.showShort(StartDaohangActivity.this,"网络未连接");
        }
    }
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save away the original text, so we still have it if the activity
        // needs to be killed while paused.
        savedInstanceState.putString("fromwhere", FROMWHERE);
        savedInstanceState.putString("saveid", id);
        savedInstanceState.putString("savedriverid", DRIVERID);
        savedInstanceState.putString("saveurl", url);
        super.onSaveInstanceState(savedInstanceState);
    }

    private void initViews() {
        mToolbar = (Toolbar) findViewById(R.id.start_daohang_toolbar);
        mToolbar.setTitle("开始送车");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
//        targetLocationText=(TextView)findViewById(R.id.start_daohang_target);
        startDaohang=(Button)findViewById(R.id.start_daohang_start_button);
        startDaohang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isConnected(StartDaohangActivity.this)) {
                    if (NetUtils.isGps(StartDaohangActivity.this)) {
                        String[] s = getMyAppNames();
                        Log.d("start", s.toString());
                        String[] r = getMyPackages();
                        Log.d("start", r.toString());
                        if (s.length == 0 && r.length == 0) {
                            Toast.makeText(StartDaohangActivity.this, "您的手机里没有合适的导航APP", Toast.LENGTH_SHORT).show();
                        } else {
                            showLongList(s, r);
                        }
                        OkHttpClientManager.postAsyn(url, new OkHttpClientManager.StringCallback() {
                            @Override
                            public void onFailure(Request request, IOException e) {
                                Toast.makeText(StartDaohangActivity.this, "开始导航失败", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onResponse(String response) {
                                Log.d("startdaohangacit", response);
                                Intent intent = new Intent();
                                intent.setAction("com.user.lanchewuyou.daohangservice");
                                intent.setPackage(getPackageName());
                                intent.putExtra("from", FROMWHERE);
                                startService(intent);
                            }
                        }, new OkHttpClientManager.Param[]{
                                new OkHttpClientManager.Param("orderid", id),
                                new OkHttpClientManager.Param("driverid", DRIVERID),
                                new OkHttpClientManager.Param("lotype", 1 + ""),
                                new OkHttpClientManager.Param("longitute", lo),
                                new OkHttpClientManager.Param("latitude", la)});
                    } else {
                         showLocationSetting();
                    }
                } else {
                    TUtils.showShort(StartDaohangActivity.this, "网络未连接");
                }


            }
        });
        endDaohang=(Button)findViewById(R.id.start_daohang_end_btn);
        endDaohang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetUtils.isServiceWork(StartDaohangActivity.this, "com.lanchewuyou.user.driver.service.DaohangService")) {
                    Intent intent = new Intent();
                    intent.setAction("com.user.lanchewuyou.daohangservice");
                    intent.setPackage(getPackageName());
                    stopService(intent);
                    lo = location.getLongitude() + "";
                    la = location.getLatitude() + "";
                    OkHttpClientManager.postAsyn(url, new OkHttpClientManager.StringCallback() {
                        @Override
                        public void onFailure(Request request, IOException e) {

                        }

                        @Override
                        public void onResponse(String response) {
                            Log.d("startdaohangacit", response);
                            if (FROMWHERE.equals("pickcar")) {
                                Intent intent = new Intent(StartDaohangActivity.this, PickCarOverActivity.class);
                                startActivity(intent);
                                finish();
                            } else if (FROMWHERE.equals("returncar")) {
                                Intent intent1 = new Intent(StartDaohangActivity.this, RerurnCarOverActivity.class);
                                startActivity(intent1);
                                finish();
                            }
                        }
                    }, new OkHttpClientManager.Param[]{
                            new OkHttpClientManager.Param("orderid", id),
                            new OkHttpClientManager.Param("driverid", DRIVERID),
                            new OkHttpClientManager.Param("longitute", lo),
                            new OkHttpClientManager.Param("latitude", la),
                            new OkHttpClientManager.Param("lotype", 3 + "")});
                } else {
                    new MaterialDialog.Builder(StartDaohangActivity.this)
                            .title("您还未开始导航")
                            .negativeText("取消")
                            .show();
                }
            }
        });
    }
    private void showLongList(String[] s, final String[]  r) {
        new MaterialDialog.Builder(this)
                .title("选择导航地图")
                .items(s)
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                        PackageManager packageManager = getPackageManager();
                        Intent intent=new Intent();
                        intent =packageManager.getLaunchIntentForPackage(r[which]);
                        startActivity(intent);
                    }
                })
                .positiveText(android.R.string.cancel)
                .show();
    }

    private void showLocationSetting(){
        new MaterialDialog.Builder(StartDaohangActivity.this)
                .title("是否进入GPS设置界面？")
                .content("您的GPS模块未打开，无法使用地图功能")
                .positiveText("确定")
                .negativeText("取消")
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, 0);
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        super.onNegative(dialog);
                    }
                })
                .show();
    }

    /**
     * 获取该手机存在的APP名字
     * @return
     */
    public String[] getMyAppNames() {
        String[]  myAppNames=new String[]{};
        List<String> list=new ArrayList<>();
        for (int i=0;i<8;i++){
            PackageManager packageManager = getPackageManager();
            Intent intent=packageManager.getLaunchIntentForPackage(packageNames[i]);
            if(intent==null){
                System.out.println("APP not found!");
            }else{
                list.add(appNames[i]);
            }

        }
        myAppNames=(String[])list.toArray(new String[list.size()]);
        return myAppNames;
    }

    /**
     * 获取该手机存在的导航APP包名
     * @return
     */
    public String[] getMyPackages() {
        String[]  myPackages=new String[]{};
        List<String> list=new ArrayList<>();
        for (int i=0;i<8;i++){
            PackageManager packageManager = getPackageManager();
            Intent intent=packageManager.getLaunchIntentForPackage(packageNames[i]);
            if(intent==null){
                System.out.println("APP not found!");
            }else{
                list.add(packageNames[i]);
            }

        }
        myPackages=(String[])list.toArray(new String[list.size()]);
        return myPackages;
    }
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("gcj02");//可选，默认gcj02，设置返回的定位结果坐标系，
        option.setScanSpan(5000);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        mLocationClient.setLocOption(option);

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_start_daohang, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
           showBackDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        showBackDialog();
    }

    private void showBackDialog(){
        new MaterialDialog.Builder(this)
                .title("退出任务")
                .content("点击确定将退出您正在执行的任务。")
                .positiveText("确定")
                .negativeText("取消")
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        finish();
                    }
                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        super.onNegative(dialog);
                    }
                })
                .show();
    }
}

